package com.zhss.eshop.order.price.promotion.reach;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhss.eshop.order.domain.dto.OrderItemDTO;
import com.zhss.eshop.order.price.promotion.PromotionActivityCalculator;
import com.zhss.eshop.order.price.promotion.PromotionActivityResult;
import com.zhss.eshop.promotion.domain.dto.PromotionActivityDTO;
import org.springframework.stereotype.Component;

/**
 * 满减类型的促销活动价格计算组件
 * @author suyuan
 *
 */
@Component
public class ReachDiscountPromotionActivityCalculator implements PromotionActivityCalculator {

//	@Autowired
//	private JsonExtractor jsonExtractor;

	/**
	 * 计算促销活动的减免金额
	 */
	@Override
	public PromotionActivityResult calculate(OrderItemDTO item,
											 PromotionActivityDTO promotionActivity) throws Exception {
		Double totalAmount = item.getPurchaseQuantity() * item.getPurchasePrice();

		String rulesJson = promotionActivity.getRule();

		JSONArray rules = JSONArray.parseArray(rulesJson);

		for(int i = 0; i < rules.size(); i++) {
			JSONObject rule = rules.getJSONObject(i);

			Double thresholdAmount = rule.getDouble( "thresholdAmount");
			Double reduceAmount = rule.getDouble( "reduceAmount");

			if(totalAmount > thresholdAmount) {
				return new PromotionActivityResult(reduceAmount);
			}
		}

		return new PromotionActivityResult();
	}

}
